from socket import *
import selectors


selector = selectors.DefaultSelector()

def accept(server, mask):
    conn, addr = server.accept()
    selector.register(conn, selectors.EVENT_READ, read)

def read(conn, mask):
    try:
        data = conn.recv(1024)
        if not data:
            conn.close()
            selector.unregister(conn)
        else:
            conn.send(b'hello')
    except Exception as e:
        print('Error:', e)
        if conn: 
            conn.close()
            selector.unregister(conn)

server = socket(AF_INET, SOCK_STREAM)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 8000))
server.listen(5)
server.setblocking(False)

selector.register(server, selectors.EVENT_READ, accept)
print('No-blocking server start at port : 8000')
while True:
    events = selector.select()
    for fd, mask in events:
        callback = fd.data
        callback(fd.fileobj, mask)
